#include "CSVParser.h"

CSVParser::CSVParser(const std::string& filename) : filename(filename) {}

CSVParser::~CSVParser() {}

bool CSVParser::loadFile() {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "Error: Could not open file " << filename << std::endl;
        return false;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::vector<std::string> row;
        std::stringstream ss(line);
        std::string cell;

        while (std::getline(ss, cell, ',')) {
            // Remove leading/trailing whitespace
            size_t first = cell.find_first_not_of(" \t\r\n\f\v");
            if (std::string::npos != first) {
                cell.erase(0, first);
                size_t last = cell.find_last_not_of(" \t\r\n\f\v");
                if (std::string::npos != last) {
                    cell.erase(last + 1);
                }
            } else {
                cell = "";
            }
            row.push_back(cell);
        }

        data.push_back(row);
    }

    file.close();
    return true;
}

std::vector<std::vector<std::string>> CSVParser::getData() {
    return data;
}

std::vector<std::string> CSVParser::getRow(int rowIndex) {
    if (rowIndex >= 0 && rowIndex < data.size()) {
        return data[rowIndex];
    } else {
        std::cerr << "Error: Row index out of bounds" << std::endl;
        return {};
    }
}

std::string CSVParser::getCell(int rowIndex, int colIndex) {
    if (rowIndex >= 0 && rowIndex < data.size() && colIndex >= 0 && colIndex < data[rowIndex].size()) {
        return data[rowIndex][colIndex];
    } else {
        std::cerr << "Error: Cell index out of bounds" << std::endl;
        return "";
    }
}